import VueSocketIO from "vue-socket.io";
import useUserStore from "@/store/modules/user";

let socket = null;
const register = () => {
  if (useUserStore().user) {
    socket = new VueSocketIO({
      debug: false,
      connection: import.meta.env.VITE_APP_SOCKET_URL,
      options: {
        transports: ["websocket", "polling"],
        query: {
          userId: useUserStore().user.userId,
        },
      },
    });
  }
};

const connect = () => {
  return new Promise((resolve, reject) => {
    if (!socket) {
      register();
    }
    if (!socket) {
      reject("sokcet 连接未创建");
    }

    if (!socket.io.connected) {
      socket.io.connect();

      socket.io.on("connect", (res) => {
        console.log("socket connect", res);
        resolve();
      });
      socket.io.on("disconnect", (res) => {
        console.log("socket disconnect", res);
      });
      socket.io.on("connect_error", (res) => {
        console.log("socket error", res);
      });
    } else {
      resolve();
    }
  });
};

const disconnect = () => {
  if (!socket) {
    return;
  }

  socket.io.disconnect();
  socket.emitter.listeners.clear();
  socket.io.removeAllListeners();
};

const addListener = (sockets, proxy) => {
  return connect().then(() => {
    Object.keys(sockets).forEach((t) => {
      if (
        t !== "subscribe" &&
        t !== "unsubscribe" &&
        !socket.emitter.listeners.has(t)
      ) {
        socket.emitter.addListener(t, sockets[t], proxy);
      }
    });
  });
};

const removeListener = (sockets, proxy) => {
  if (!socket) {
    return;
  }

  Object.keys(sockets).forEach((t) => {
    socket.emitter.removeListener(t, proxy);
  });
};

const emit = (key, value) => {
  return connect().then(() => {
    socket.io.emit(key, value);
  });
};

export { connect, disconnect, addListener, removeListener, emit };
